<template>
    <div class="register-container">
        <el-card class="register-card" shadow="hover">
            <div slot="header" class="clearfix">
                <span style="font-size: 20px; font-weight: bold">用户注册</span>
            </div>

            <el-form ref="registerForm" :model="registerForm" :rules="rules" label-width="100px" label-position="top">
                <!-- 1. 用户类型选择 -->
                <el-form-item label="用户类型" prop="userType">
                    <el-select v-model="registerForm.userType" placeholder="请选择用户类型" clearable>
                        <el-option label="普通用户" value="普通用户"></el-option>
                        <el-option label="vip用户" value="vip用户"></el-option>
                    </el-select>
                    <div class="user-type-tip" v-if="registerForm.userType">
                        <i class="el-icon-info"></i>
                        <span v-if="registerForm.userType === '普通用户'">普通用户：享受基础服务，无额外权益</span>
                        <span v-if="registerForm.userType === 'vip用户'">vip用户用户：享受专属客服、数据优先加载、免广告等权益</span>
                    </div>
                </el-form-item>

                <!-- 2. 头像上传部分 -->
                <div class="avatar-section">
                    <div class="avatar-wrapper">
                        <img class="avatar-preview" :src="registerForm.headPicture" alt="用户头像"
                            v-if="registerForm.headPicture">
                        <i v-else class="el-icon-plus avatar-placeholder"></i>
                    </div>
                    <div class="avatar-actions">
                        <input type="file" accept="image/*" hidden ref="fileInput" @change="handleFileChange">
                        <el-button type="primary" icon="el-icon-picture-outline" @click="triggerFileInput">
                            选择头像
                        </el-button>
                    </div>
                </div>

                <!-- 3. 用户名 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerForm.username" placeholder="4-16位字母数字组合" clearable></el-input>
                </el-form-item>

                <!-- 4. 密码 -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="registerForm.password" placeholder="至少6位，包含字母和数字" show-password
                        clearable></el-input>
                </el-form-item>

                <!-- 5. 确认密码 -->
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="registerForm.confirmPassword" placeholder="请再次输入密码" show-password
                        clearable></el-input>
                </el-form-item>

                <!-- 6. 提交按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="submitForm()" style="width: 100%" :loading="loading">
                        立即注册
                    </el-button>
                </el-form-item>

                <div class="login-link">
                    已有账号？<router-link to="/login">立即登录</router-link>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { registerUser } from '@/api/admin/User'
import { upload } from '@/api/common/common'

export default {
    name: 'RegisterPage',
    data() {
        const validatePassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入密码'))
            } else if (value.length < 6) {
                callback(new Error('密码长度不能少于6位'))
            } else if (!/(?=.*[A-Za-z])(?=.*\d)/.test(value)) {
                callback(new Error('密码必须包含字母和数字'))
            } else {
                if (this.registerForm.confirmPassword !== '') {
                    this.$refs.registerForm.validateField('confirmPassword')
                }
                callback()
            }
        }

        const validateConfirmPassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.registerForm.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }

        const validateUsername = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入用户名'))
            } else if (value.length < 4 || value.length > 16) {
                callback(new Error('用户名长度应为4-16位'))
            } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
                callback(new Error('用户名只能包含字母和数字'))
            } else {
                callback()
            }
        }

        return {
            loading: false,
            registerForm: {
                headPicture: '',
                username: '',
                password: '',
                confirmPassword: '',
                userType: '普通用户' // 默认改为普通用户
            },
            rules: {
                userType: [
                    { required: true, message: '请选择用户类型', trigger: 'change' }
                ],
                username: [
                    { required: true, validator: validateUsername, trigger: 'blur' }
                ],
                password: [
                    { required: true, validator: validatePassword, trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        triggerFileInput() {
            this.$refs.fileInput.click()
        },
        formatImagePath(path) {
            if (!path) return this.defaultAvatar;

            console.log('原始路径:', path);
            // 清理路径中的引号和前后空格
            let cleanPath = path.replace(/["']/g, '').trim();
            console.log('清理后路径:', cleanPath);

            // 匹配所有系统路径（Windows: C:\a\b.png，Linux: /home/a/b.png），提取最后一个 / 或 \ 后的文件名
            const fileNameMatch = cleanPath.match(/([^\\/]+)\.(\w+)$/);
            if (fileNameMatch && fileNameMatch[1] && fileNameMatch[2]) {
                const fileName = `${fileNameMatch[1]}.${fileNameMatch[2]}`;
                console.log('提取的文件名:', fileName);
                const imageUrl = `http://localhost:8090/images/${fileName}`;
                console.log('生成的图片URL:', imageUrl);
                return imageUrl;
            }
            return cleanPath || this.defaultAvatar;
        },

        async handleFileChange(e) {
            const file = e.target.files[0];
            if (!file) return;

            // 添加文件验证
            if (!this.beforeUpload(file)) {
                this.$message.warning('请上传JPG/PNG格式图片，且大小不超过2MB');
                return;
            }

            const reader = new FileReader();
            reader.onload = () => {
                upload(file)
                    .then((response) => {
                        console.log(response, "response");

                        this.registerForm.headPicture = this.formatImagePath(response);
                        this.$message.success('头像上传成功');
                    })
                    .catch(error => {
                        this.$message.error('头像上传失败：' + (error.message || '未知错误'));
                    });
            };
            reader.readAsDataURL(file);
        },

        beforeUpload(file) {
            // const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type);
            // const isLt2M = file.size / 1024 / 1024 < 2;
            // return isImage && isLt2M;
            return true;
        },

        // 修复：改进表单验证和错误处理
        submitForm() {
            this.$refs.registerForm.validate((valid, fields) => {
                if (valid) {
                    this.loading = true;

                    const userData = {
                        uid: this.registerForm.userType === '普通用户' ? '普通用户' : 'VIP用户',
                        name: this.registerForm.username,
                        password: this.registerForm.password, // 使用password而不是confirmPassword
                        headPicture: this.registerForm.headPicture,
                    }

                    registerUser(userData)
                        .then(res => {
                            this.loading = false;

                            if (res.data.code === 1) {
                                const userTypeText = this.registerForm.userType === '普通用户' ? '普通用户' : 'VIP用户';
                                this.$message.success(`恭喜！${userTypeText}注册成功`);
                                // 注册成功后清空表单参数
                                this.registerForm = {
                                    headPicture: '',
                                    username: '',
                                    password: '',
                                    confirmPassword: '',
                                    userType: '普通用户' // 保留默认用户类型
                                };
                                // 重置文件输入框（避免重复上传同一文件不触发change事件）
                                this.$refs.fileInput.value = '';
                            } else {
                                this.$message.error(res.msg || '注册失败，请重试');
                            }
                        })
                        .catch(error => {
                            this.loading = false;
                            console.error('注册失败:', error);
                            this.$message.error('注册接口异常：' + (error.message || '请联系管理员'));
                        });
                } else {
                    // 修复：显示具体的验证错误信息
                    const firstErrorField = Object.keys(fields)[0];
                    if (firstErrorField) {
                        const errorMessage = fields[firstErrorField][0].message;
                        this.$message.error(`请修正以下问题：${errorMessage}`);

                        // 滚动到第一个错误字段
                        this.$nextTick(() => {
                            const errorElement = document.querySelector('.is-error');
                            if (errorElement) {
                                errorElement.scrollIntoView({
                                    behavior: 'smooth',
                                    block: 'center'
                                });
                            }
                        });
                    } else {
                        this.$message.error('请完善表单信息');
                    }
                }
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
    padding: 20px;

    .register-card {
        width: 450px;
        border-radius: 8px;

        ::v-deep .el-card__header {
            border-bottom: none;
            padding-bottom: 0;
            text-align: center;
        }
    }

    .user-type-tip {
        margin-top: 8px;
        font-size: 12px;
        color: #606266;
        display: flex;
        align-items: center;
        gap: 4px;

        .el-icon-info {
            color: #409EFF;
        }
    }

    .avatar-section {
        text-align: center;
        margin-bottom: 24px;

        .avatar-wrapper {
            display: inline-block;
            position: relative;
            margin-bottom: 10px;
            cursor: pointer;

            .avatar-preview {
                width: 120px;
                height: 120px;
                border-radius: 6px;
                object-fit: cover;
                border: 2px dashed #ebeef5;
                box-sizing: border-box;
            }

            .avatar-placeholder {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 120px;
                height: 120px;
                font-size: 32px;
                color: #8c939d;
                border: 2px dashed #dcdfe6;
                border-radius: 6px;
                background-color: #f8f9fa;
            }
        }

        .avatar-actions {
            text-align: center;

            input[type="file"] {
                display: none;
            }
        }
    }

    .login-link {
        text-align: center;
        margin-top: 20px;
        color: #606266;

        a {
            color: #409EFF;
            text-decoration: none;

            &:hover {
                text-decoration: underline;
            }
        }
    }
}
</style>